const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('🔔 初始化通知集合')
  
  try {
    // 检查 user_notifications 集合是否存在
    let collections = []
    try {
      const result = await db.listCollections()
      collections = result.data.map(item => item.name)
      console.log('📋 现有集合:', collections)
    } catch (error) {
      console.log('⚠️ 无法获取集合列表，可能是权限问题')
    }
    
    // 创建测试通知数据
    const testNotifications = [
      {
        type: 'system_notice',
        title: '欢迎使用数智匠心工程',
        content: '欢迎您使用数智匠心工程平台！我们致力于为您提供优质的工程服务。',
        targetOpenid: 'system', // 系统通知
        isRead: false,
        data: {
          noticeType: 'welcome'
        },
        createTime: new Date()
      },
      {
        type: 'audit_result',
        title: '施工队伍审核通过',
        content: '恭喜！您的个人师傅"张师傅"注册申请已通过审核，现在可以接收预约服务订单了。',
        targetOpenid: 'demo_user', // 演示用户
        isRead: false,
        data: {
          teamId: 'demo_team_001',
          teamName: '张师傅',
          teamType: '个人师傅',
          action: 'approve',
          auditTime: new Date()
        },
        createTime: new Date()
      },
      {
        type: 'audit_result',
        title: '施工队伍审核拒绝',
        content: '很抱歉，您的施工公司"XX建筑公司"注册申请未通过审核。您可以根据拒绝原因修改信息后重新提交申请。',
        targetOpenid: 'demo_user_2', // 演示用户2
        isRead: false,
        data: {
          teamId: 'demo_team_002',
          teamName: 'XX建筑公司',
          teamType: '施工公司',
          action: 'reject',
          reason: '资质证明不完整，请补充相关证书',
          auditTime: new Date()
        },
        createTime: new Date()
      }
    ]
    
    // 尝试插入测试数据
    const insertResults = []
    for (const notification of testNotifications) {
      try {
        const result = await db.collection('user_notifications').add({
          data: notification
        })
        insertResults.push({
          success: true,
          id: result._id,
          title: notification.title
        })
        console.log(`✅ 插入通知成功: ${notification.title}`)
      } catch (error) {
        insertResults.push({
          success: false,
          error: error.message,
          title: notification.title
        })
        console.error(`❌ 插入通知失败: ${notification.title}`, error)
      }
    }
    
    // 查询插入的数据
    let queryResult = null
    try {
      queryResult = await db.collection('user_notifications')
        .orderBy('createTime', 'desc')
        .limit(10)
        .get()
      console.log(`📬 查询到 ${queryResult.data.length} 条通知记录`)
    } catch (error) {
      console.error('❌ 查询通知记录失败:', error)
    }
    
    return {
      success: true,
      message: '通知集合初始化完成',
      data: {
        collections: collections,
        insertResults: insertResults,
        totalNotifications: queryResult ? queryResult.data.length : 0,
        notifications: queryResult ? queryResult.data : []
      }
    }
    
  } catch (error) {
    console.error('❌ 初始化通知集合失败:', error)
    return {
      success: false,
      error: error.message || '初始化失败'
    }
  }
}
